package com.sunyu.springboot.component;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

/**
 * @author yu 2018/12/11.
 */
public class RestTemplateClient extends RestTemplate{

    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateClient.class);

    public RestTemplateClient(){
    }

    public RestTemplateClient(ClientHttpRequestFactory requestFactory){
        super(requestFactory);
    }

    /**
     * 发送json参数
     *
     * @param url
     * @param params
     * @return
     */
    public String postJson(String url, Object params) {
        RestTemplate restTemplate = new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofSeconds(2))
                .setReadTimeout(Duration.ofSeconds(2))
                .build();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));

        String bodyData = JSON.toJSONString(params);
        LOGGER.debug("Request url:{}", url);
        LOGGER.debug("Request body:{}", bodyData);
        long startTime = System.currentTimeMillis();
        HttpEntity<String> httpEntity = new HttpEntity<>(bodyData, headers);
        String result = restTemplate.postForObject(url, httpEntity, String.class);
        long endTime = System.currentTimeMillis();
        LOGGER.debug("url request costTime:{} ms", (endTime - startTime));
        LOGGER.debug("The {} response is: {}", url, result);
        return result;
    }


}
